import Database from 'better-sqlite3'
import path from 'node:path'
import logger from '../utils/logger.js'
import { SQL } from './sql.js'
import config from '../../config.json' assert { type: 'json' }

class DB {
    constructor (config) {
        const {
            dbPath= 'data.db',
            tables = []
        } = config
        this.dbPath = path.join(import.meta.dirname, dbPath)
        this.tables = tables
        this.database = new Database(this.dbPath, { verbose: logger.info })
    }

    createAllTable(tableConfig) {
        const func = this.database.transaction((tables) => {
            tables.forEach(table => {
                const { name = '', columns = [] } = table || {}
                if (!name || columns.length === 0) {
                    logger.error(`can\'t not create table. tableConfig: ${JSON.stringify(tableConfig)}`)
                    return 0
                }
                const sqlSyntax = SQL.createTable(name, columns)
                this.database.prepare(sqlSyntax).run()
            })
        })
        func(this.tables)
    }
}

export const db = new DB(config.db)
